package com.yhhvip.lottery.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yhhvip.exception.BusinessException;
import com.yhhvip.lottery.dao.mybatis.mapper.LotActivityParticipantsMapper;
import com.yhhvip.lottery.dao.mybatis.mapper.LotSysUserRoleMapper;
import com.yhhvip.lottery.dao.mybatis.mapper.LotUserMapper;
import com.yhhvip.lottery.dao.mybatis.model.*;
import com.yhhvip.lottery.domain.*;
import com.yhhvip.lottery.domain.res.ResLotUser;
import com.yhhvip.lottery.domain.res.ResUserLotteryVo;
import com.yhhvip.lottery.service.LotUserService;
import com.yhhvip.utils.IdWorker;
import com.yhhvip.utils.WxUtil.HttpUtil;
import com.yhhvip.utils.WxUtil.WxConfigUtil;
import com.yhhvip.utils.WxUtil.WxunionidUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author XOu
 * @version 1.0
 * @description 用户相关业务处理层
 * @date 2018/6/18
 */
@Service
@Slf4j
@Transactional
public class LotUserServiceImpl implements LotUserService {

    @Autowired
    private LotUserMapper userMapper;

    @Autowired
    private LotActivityParticipantsMapper activityParticipantsMapper;

    @Autowired
    private LotSysUserRoleMapper userRoleMapper;

    @Override
    public Long add(UserVo userVo) throws Exception {
        Map<String, String> map = getWxUserInfo(userVo.getCode());
        String wxUserInfo = WxunionidUtil.decrypt2(userVo.getEncryptedData(), map.get("sessionKey"), userVo.getIv(), "UTF-8");
        JSONObject jsonObject = JSON.parseObject(wxUserInfo);
        String unionId = String.valueOf(jsonObject.get("unionid"));
        LotUser user = new LotUser();
        user.setCreateTime(new Date());
        user.setHeadUrl(userVo.getHeadUrl());
        user.setNickName(userVo.getNickName());
        user.setStatus((byte) 1);
        user.setType((byte) 1);
        user.setOpenId(map.get("openid"));
        user.setUnionId(unionId);
        int i = userMapper.insertSelective(user);
        if (1 == i) {
            return user.getId();
        }
        return null;
    }

    @Override
    public int update(UserInfoVo userInfoVo) {
        LotUser lotUser = new LotUser();
        lotUser.setId(userInfoVo.getId());
        lotUser.setNickName(userInfoVo.getNickName());
        lotUser.setHeadUrl(userInfoVo.getHeadUrl());
        lotUser.setStatus(userInfoVo.getStatus());
        return userMapper.updateByPrimaryKeySelective(lotUser);
    }

    @Override
    public PageInfo<LotUser> selectUsers(UserQueryVo userQueryVo) {
        PageHelper.startPage(userQueryVo.getPageNum(), userQueryVo.getPageSize());
        List<LotUser> userList = userMapper.selectUsers(userQueryVo);
        PageInfo<LotUser> userPageInfo = new PageInfo<>(userList);
        return userPageInfo;
    }


    @Override
    public void testInsert() {
        for (int i = 0; i < 1000; i++) {
            LotUser lotUser = new LotUser();
            IdWorker instance = IdWorker.getInstance();
            lotUser.setUnionId(instance.nextId() + "");
            lotUser.setHeadUrl("www.baidu.com");
            lotUser.setNickName("test".concat(i + ""));
            lotUser.setCreateTime(new Date());
            userMapper.insertSelective(lotUser);
        }
    }

    @Override
    public LotUser selectUserById(Long id) {
        LotUserExample lotUserExample = new LotUserExample();
        lotUserExample.createCriteria().andIdEqualTo(id).andTypeEqualTo((byte) 1);
        List<LotUser> lotUsers = userMapper.selectByExample(lotUserExample);
        if (null != lotUsers && lotUsers.size() > 0) {
            LotUser user = lotUsers.get(0);
            user.setUnionId(null);
            user.setOpenId(null);
            user.setPassword(null);
            return user;
        }
        return null;
    }

    @Override
    public PageInfo<ResUserLotteryVo> selectUserLottery(ReqUserLotteryQueryVo reqUserLotteryQueryVo) {
        PageHelper.startPage(reqUserLotteryQueryVo.getPageNum(), reqUserLotteryQueryVo.getPageSize());
        List<ResUserLotteryVo> userLotteryVos = userMapper.selectUserLottery(reqUserLotteryQueryVo);
        PageInfo<ResUserLotteryVo> userLotteryVoPageInfo = new PageInfo<>(userLotteryVos);
        return userLotteryVoPageInfo;
    }

    @Override
    public int userAddress(ReqUserAddress reqUserAddress) {
        long userId = reqUserAddress.getUserId();
        String address = reqUserAddress.getAddress();
        long activityId = reqUserAddress.getActivityId();
        LotActivityParticipants activityParticipants = new LotActivityParticipants();
        activityParticipants.setUserAddress(address);
        LotActivityParticipantsExample participantsExample = new LotActivityParticipantsExample();
        participantsExample.createCriteria().andUserIdEqualTo(userId).andActivityIdEqualTo(activityId).andIsWonEqualTo((byte) 1).andShipStatusEqualTo((byte) 0);
        return activityParticipantsMapper.updateByExampleSelective(activityParticipants, participantsExample);
    }

    @Override
    public int affirmShipments(ReqAffirmShipments reqAffirmShipments) {
        LotActivityParticipants participants = new LotActivityParticipants();
        participants.setExpNum(reqAffirmShipments.getExpNum());
        participants.setExpCompany(reqAffirmShipments.getExpCompany());
        participants.setShipStatus((byte) 1);
        LotActivityParticipantsExample participantsExample = new LotActivityParticipantsExample();
        participantsExample.createCriteria().andUserIdEqualTo(reqAffirmShipments.getUserId()).andActivityIdEqualTo(reqAffirmShipments.getActivityId()).andShipStatusEqualTo((byte) 0);
        return activityParticipantsMapper.updateByExampleSelective(participants, participantsExample);
    }

    @Override
    public PageInfo<ResLotUser> selectSysUsersByPage(ReqSearchUserVo reqSearchUserVo) {
        PageHelper.startPage(reqSearchUserVo.getPageNum(), reqSearchUserVo.getPageSize());
        List<ResLotUser> userLotteryVos = userMapper.selectSysUsersByPage(reqSearchUserVo);
        PageInfo<ResLotUser> userLotteryVoPageInfo = new PageInfo<>(userLotteryVos);
        return userLotteryVoPageInfo;
    }

    @Override
    public int addSysUserRole(ResLotSysUserRole resLotSysUserRole) {
        //先删除
        LotSysUserRoleExample userRoleExample = new LotSysUserRoleExample();
        userRoleExample.createCriteria().andUserIdEqualTo(resLotSysUserRole.getUserId());
        userRoleMapper.deleteByExample(userRoleExample);
        //再添加
        String[] roleids = resLotSysUserRole.getRoleId().split(",");
        int i = 0;
        for (String roleId : roleids) {
            LotSysUserRole u = new LotSysUserRole();
            u.setUserId(resLotSysUserRole.getUserId());
            u.setRoleId(Long.parseLong(roleId));
            i = userRoleMapper.insertSelective(u);
        }
        return i;
    }

    @Override
    public LotUser selectByUsername(String username) {
        LotUserExample lotUserExample = new LotUserExample();
        lotUserExample.createCriteria().andUsernameEqualTo(username);
        List<LotUser> users = userMapper.selectByExample(lotUserExample);
        if (users.size() > 0) {
            return users.get(0);
        }
        return null;
    }

    @Override
    public Long saveSysUser(ReqAddSysUserVo user) {
        LotUser lotUser = new LotUser();
        BeanUtils.copyProperties(user, lotUser);
        lotUser.setType((byte) 2);
        lotUser.setCreateTime(new Date());
        int i = userMapper.insertSelective(lotUser);
        if (1 == i) {
            return lotUser.getId();
        }
        return null;
    }

    @Override
    public int delSysUser(Long userId) {
        //删除用户表
        int i = userMapper.deleteByPrimaryKey(userId);
        //删除用户角色表
        LotSysUserRoleExample userRoleExample = new LotSysUserRoleExample();
        userRoleExample.createCriteria().andUserIdEqualTo(userId);
        userRoleMapper.deleteByExample(userRoleExample);
        return i;
    }

    /**
     * @param code 微信用户code
     * @author XOu
     * @description 获取微信用户信息
     * @version 1.0
     * @date 2018/7/1
     * @modified
     */
    public Map<String, String> getWxUserInfo(String code) {
        String openParam = "appid=" + WxConfigUtil.LOTTERY_APPID + "&secret=" + WxConfigUtil.LOTTERY_SECRT + "&js_code=" + code + "&grant_type=authorization_code";
        String openJsonStr = HttpUtil.SendGET("https://api.weixin.qq.com/sns/jscode2session", openParam);
        log.info("获取微信用户unionId接口返回参数{}", openJsonStr);
        Map openMap = JSON.parseObject(openJsonStr);
        if (openMap.containsKey("errcode")) {
            log.error("==========调用微信接口异常{}", String.valueOf(openMap.get("errmsg")));
            throw new BusinessException("调用微信接口异常");
        }
        String sessionKey = String.valueOf(openMap.get("session_key"));
        String openid = String.valueOf(openMap.get("openid"));
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("sessionKey", sessionKey);
        resultMap.put("openid", openid);
        return resultMap;
    }

    @Override
    public Map<String, Object> checkoutUserExist(String code) {
        Map<String, String> userInfo = getWxUserInfo(code);
        if (null == userInfo || userInfo.isEmpty()) {
            throw new BusinessException("用户信息查询失败");
        }
        LotUserExample userExample = new LotUserExample();
        userExample.createCriteria().andOpenIdEqualTo(userInfo.get("openid"));
        List<LotUser> users = userMapper.selectByExample(userExample);
        Map<String, Object> result = new HashMap<>();;
        if (null != users && users.size() > 0) {
            LotUser user = users.get(0);
            result.put("isExist", 1);
            result.put("userId", user.getId());
            return result;
        } else {
            result.put("isExist", 0);
            result.put("userId", null);
            return result;
        }
    }


}
